<?php
namespace app\bsadmin\controller;
use think\facade\Cache;
use think\facade\View;
use think\facade\Db;
use think\facade\Validate;
use app\common\model\User as UserModel;
use app\common\model\Article as ArticleModel;
use app\common\model\ArticleContent as ArticleContentModel;
use app\common\model\ArticleCate as ArticleCateModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\controller\Posters as PostersController;
use app\common\model\Area as AreaModel;
use app\common\model\CompanyIndustry as CompanyIndustryModel;
use helper\Baidu;
class Article extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['cid']) {
                $where[]=['article.cid','=',$G['cid']];
            }
            if ($G['title']) {
                $where[]=['article.title','like','%'.$G['title'].'%'];
            }
            if ($G['status']!='all') {
                $where[]=['article.status','=',$G['status']];
            }
            $Data=ArticleModel::alias('article')->where($where)
                ->join('article_cate cate','cate.id=article.cid','LEFT')
                ->field('article.*,cate.title as cate_title')
                ->order('article.sort asc,article.id desc')->paginate($G['pageSize'])
                ->each(function($v){
                    $v['start_time']=$v['start_time']?date('Y-m-d',$v['start_time']):'';
                    $v['end_time']=$v['end_time']?date('Y-m-d',$v['end_time']):'';
                    $v['thumb']=$v['thumb']?config('web.imgurl').$v['thumb']:'';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            $cate=ArticleCateModel::getCateSelect()->toArray();
            View::assign('cate',getTree($cate));
            return View::fetch();
        }
    }
    public function recycleBin()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['cid']) {
                $where[]=['article.cid','=',$G['cid']];
            }
            if ($G['title']) {
                $where[]=['article.title','like','%'.$G['title'].'%'];
            }
            if ($G['status']!='all') {
                $where[]=['article.status','=',$G['status']];
            }
            $Data=ArticleModel::onlyTrashed()->alias('article')->where($where)
                ->join('article_cate cate','cate.id=article.cid','LEFT')
                ->field('article.*,cate.title as cate_title')
                ->order('article.delete_time desc')->paginate($G['pageSize'])
                ->each(function($v){
                    $v['start_time']=$v['start_time']?date('Y-m-d',$v['start_time']):'';
                    $v['end_time']=$v['end_time']?date('Y-m-d',$v['end_time']):'';
                    $v['thumb']=$v['thumb']?config('web.imgurl').$v['thumb']:'';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            $cate=ArticleCateModel::getCateSelect()->toArray();
            View::assign('cate',getTree($cate));
            return View::fetch();
        }
    }
    /**
     * 编辑文章
     */
    public function editArticle($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:200',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过200个字符',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $ArticleModel=ArticleModel::find($id);
            $ArticleModel->title    = $D['title'];
            $ArticleModel->alias    = $D['alias'];
            $ArticleModel->source   = $D['source'];
            $ArticleModel->desc     = $D['desc'];
            $ArticleModel->status   = $D['status'];
            $ArticleModel->status_alias= $D['status_alias'];
            $ArticleModel->view     = $D['view'];
            $ArticleModel->thumb    = $D['thumb'];
            $ArticleModel->cid      = $D['cid'];
            $ArticleModel->force_alert= $D['force_alert'];
            $ArticleModel->cla= $D['cla'];
            $ArticleModel->industry= $D['industry'];
            $ArticleModel->sort= $D['sort'];
            if (!empty($D['area'])&&count($D['area'])>=3) {
                $ArticleModel->province  = $D['area'][0];
                $ArticleModel->city      = $D['area'][1];
                $ArticleModel->area      = $D['area'][2];
            }else{
                $ArticleModel->province  = null;
                $ArticleModel->city      = null;
                $ArticleModel->area      = null;
            }

            if (strtotime($D['start_time'])){
                $ArticleModel->start_time= strtotime($D['start_time'].' 08:00:00');
            }else{
                $ArticleModel->start_time= null;
            }
            if (strtotime($D['end_time'])){
                $ArticleModel->end_time= strtotime($D['end_time'].' 23:59:59');
            }else{
                $ArticleModel->end_time= null;
            }
            $ArticleContentModel=ArticleContentModel::where(['tid'=>$id])->find();
            $ArticleContentModel->content=$D['content'];
            // 启动事务
            Db::startTrans();
            try {
                $ArticleModel->save();
                $ArticleContentModel->save();
                // 提交事务
                Db::commit();
                $this->setArticleCache($ArticleModel->id);
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $industry=CompanyIndustryModel::getSelect(['pid'=>0]);
            View::assign('industry',$industry);
            $area=AreaModel::getCache();
            View::assign('area',$area);
            $cate=ArticleCateModel::getCateSelect()->toArray();
            View::assign('cate',getTree($cate));
            $status_alias=StatusAliasModel::getSelect('article/status_alias');
            View::assign('status_alias',$status_alias);
            $Find=ArticleModel::alias('article')->where(['article.id'=>$id])
                ->join('article_content content','content.tid = article.id','LEFT')->field('article.*,content.content')
                ->withAttr('start_time',function($v,$d){
                    return $v?date('Y-m-d',$v):'';
                })
                ->withAttr('end_time',function($v,$d){
                    return $v?date('Y-m-d',$v):'';
                })->find();
            View::assign('Find',$Find);
            View::assign('webtitle','编辑【'.$Find->title.'】文章');
            return View::fetch('add_article');
        }
    }
    /**
     * 发布文章
     */
    public function addArticle()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:200',
	            'alias'  	=> 'unique:article',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过200个字符',
	            'alias.unique' 	=> '别名已存在',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $ArticleModel=new ArticleModel;
            $ArticleModel->title    = $D['title'];
            $ArticleModel->alias    = $D['alias'];
            $ArticleModel->source   = $D['source'];
            $ArticleModel->desc   	= $D['desc'];
            $ArticleModel->status   = $D['status'];
            $ArticleModel->status_alias= $D['status_alias'];
            $ArticleModel->view   	= $D['view'];
            $ArticleModel->thumb   	= $D['thumb'];
            $ArticleModel->cid      = $D['cid'];
            $ArticleModel->force_alert= $D['force_alert'];
            $ArticleModel->cla= $D['cla'];
            $ArticleModel->industry= $D['industry'];
            $ArticleModel->sort= $D['sort'];
            if (!empty($D['area'])&&count($D['area'])>=3) {
                $ArticleModel->province  = $D['area'][0];
                $ArticleModel->city      = $D['area'][1];
                $ArticleModel->area      = $D['area'][2];
            }else{
                $ArticleModel->province  = null;
                $ArticleModel->city      = null;
                $ArticleModel->area      = null;
            }

            if (strtotime($D['start_time']))
                $ArticleModel->start_time= strtotime($D['start_time'].' 08:00:00');
            if (strtotime($D['end_time']))
                $ArticleModel->end_time= strtotime($D['end_time'].' 23:59:59');
            $ArticleContentModel=new ArticleContentModel;
            $ArticleContentModel->content=$D['content'];
            // 启动事务
            Db::startTrans();
            try {
                $ArticleModel->save();
                $ArticleContentModel->tid=$ArticleModel->id;
                $ArticleContentModel->save();
                // 提交事务
                Db::commit();
                $this->setArticleCache($ArticleModel->id);
                Baidu::post(config('web.url').'/article/content/'.$ArticleModel->id.'.html');
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $industry=CompanyIndustryModel::getSelect(['pid'=>0]);
            View::assign('industry',$industry);
            $area=AreaModel::getCache();
            View::assign('area',$area);
            $cid=request()->get('cid');
            if($cid){
                $ArticleCateModel=ArticleCateModel::where(['id'=>$cid])->find();
                $ArticleCateModel&&View::assign('webtitle','发布'.$ArticleCateModel->title);
            }
            $cate=ArticleCateModel::getCateSelect()->toArray();
            View::assign('cate',getTree($cate));
            $status_alias=StatusAliasModel::getSelect('article/status_alias');
            View::assign('status_alias',$status_alias);
            return View::fetch();
        }
    }
    public function setArticleCid($id,$cid)
    {
        $ArticleModel=ArticleModel::find($id);
        $ArticleModel->cid=$cid;
        if ($ArticleModel->save()) {
            $this->setArticleCache($id);
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    /**
     * 设置文章状态
     */
    public function setArticleStatus($id,$status)
    {
        $ArticleModel=ArticleModel::find($id);
        $ArticleModel->status=$status;
        if ($ArticleModel->save()) {
            $this->setArticleCache($id);
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function setArticleDelete($id)
    {
        $ArticleModel=ArticleModel::find($id);
        if($ArticleModel){
            if ($ArticleModel->delete()) {
                $this->deleteArticleCache($ArticleModel);
                return $this->ajaxReturn();
            }else{
                return $this->ajaxReturn('保存失败，请重试',-100);
            }
        }else{
            $ArticleModel=ArticleModel::onlyTrashed()->find($id);
            if($ArticleModel){
                if (empty(request()->get('force'))) {
                    if ($ArticleModel->restore()) {
                        return $this->ajaxReturn();
                    } else {
                        return $this->ajaxReturn('保存失败，请重试', -100);
                    }
                }else{
                    if ($ArticleModel->force()->delete()) {
                        return $this->ajaxReturn();
                    } else {
                        return $this->ajaxReturn('保存失败，请重试', -100);
                    }
                }
            }
        }
        return $this->ajaxReturn('文章不存在',-100);
    }
    protected function deleteArticleCache($Model)
    {
        Cache::delete('article.id_'.$Model->id);
        Cache::delete('article.alias_'.$Model->alias);
    }
    /**
     * 缓存文章
     */
    protected function setArticleCache($id)
    {
        $article=ArticleModel::field('id,alias')->find($id);
        if ($article) {
            if ($article->alias)
                Cache::set('article_update_cache.'.$article->alias,1);
            Cache::set('article_update_cache.id_'.$article->id,1);
            $qrsize=new \stdClass;
            $qrsize->size=140;
            PostersController::CreateArticleQRCode($article,$qrsize);
        }
    }
    public function agreement()
    {
        $cid=ArticleCateModel::where(['alias'=>'agreement'])->value('id');
        View::assign('cid',$cid);
        return View::fetch();
    }
    public function publicsArticle()
    {
        $cid=ArticleCateModel::where(['alias'=>'publics'])->value('id');
        View::assign('cid',$cid);
        return View::fetch('agreement');
    }
    public function notice()
    {
        $cid=ArticleCateModel::where(['alias'=>'article_notice'])->value('id');
        View::assign('cid',$cid);
        return View::fetch('agreement');
    }
    /**
     * 文章分类
     */
    public function cate()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            if (empty($G['cid'])) {
                return $this->ajaxReturn('',0,ArticleCateModel::getSelect(['pid'=>0]));
            }else{
                return $this->ajaxReturn('',0,ArticleCateModel::getSelect(['pid'=>$G['cid']]));
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 编辑文章分类
     */
    public function editCate($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:50',
	            'alias'  	=> 'unique:articleCate',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过50个字符',
	            'alias.unique' 	=> '别名已存在',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $ArticleCateModel=ArticleCateModel::find($id);
            $ArticleCateModel->title    = $D['title'];
            $ArticleCateModel->alias    = $D['alias'];
            $ArticleCateModel->pc_show  = $D['pc_show'];
            $ArticleCateModel->app_show = $D['app_show'];
            $ArticleCateModel->h5_show  = $D['h5_show'];
            $ArticleCateModel->mp_show  = $D['mp_show'];
            $ArticleCateModel->alipay_show  = $D['alipay_show'];
            $ArticleCateModel->baidu_show  = $D['baidu_show'];
            $ArticleCateModel->toutiao_show  = $D['toutiao_show'];
            $ArticleCateModel->kuaishou_show  = $D['kuaishou_show'];
            if (!empty($D['pid'])) 
	            $ArticleCateModel->pid   	= $D['pid'];
            if (!empty($D['sort'])) 
            	$ArticleCateModel->sort   	= $D['sort'];
            if($ArticleCateModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $cate=ArticleCateModel::getCate()->toArray();
            View::assign('cate',$cate);
            $Find=ArticleCateModel::where(['id'=>$id])->find();
            View::assign('Find',$Find);
            return View::fetch('add_cate');
        }
    }
    /**
     * 添加文章分类
     */
    public function addCate()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:50',
	            'alias'  	=> 'unique:articleCate',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过50个字符',
	            'alias.unique' 	=> '别名已存在',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $ArticleCateModel=new ArticleCateModel;
            $ArticleCateModel->title    = $D['title'];
            $ArticleCateModel->alias    = $D['alias'];
            $ArticleCateModel->pc_show  = $D['pc_show'];
            $ArticleCateModel->app_show = $D['app_show'];
            $ArticleCateModel->h5_show  = $D['h5_show'];
            $ArticleCateModel->mp_show  = $D['mp_show'];
            $ArticleCateModel->alipay_show  = $D['alipay_show'];
            $ArticleCateModel->baidu_show  = $D['baidu_show'];
            $ArticleCateModel->toutiao_show  = $D['toutiao_show'];
            $ArticleCateModel->kuaishou_show  = $D['kuaishou_show'];
            if (!empty($D['pid'])) 
	            $ArticleCateModel->pid   	= $D['pid'];
            if (!empty($D['sort'])) 
            	$ArticleCateModel->sort   	= $D['sort'];
            if($ArticleCateModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $cate=ArticleCateModel::getCate()->toArray();
            View::assign('cate',$cate);
            return View::fetch();
        }
    }
    public function delCate($id)
    {
        if (ArticleModel::where(['cid'=>$id])->count())
            return $this->ajaxReturn('该分类下还有文章，无法删除',-100);
        if (ArticleCateModel::where(['pid'=>$id])->count())
            return $this->ajaxReturn('该分类下还有分类，无法删除',-100);
        if (ArticleCateModel::where(['id'=>$id])->delete()) {
            return $this->ajaxReturn('已删除');
        }else{
            return $this->ajaxReturn('删除失败',-100);
        }
    }
}
